package com.example.forum.services.impl;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.dao.ArticleMapper;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.Article;
import com.example.forum.model.Board;
import com.example.forum.model.User;
import com.example.forum.services.IArticleService;
import com.example.forum.services.IBoradService;
import com.example.forum.services.IUserService;
import com.example.forum.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.stream.Collectors;


@Service
@Slf4j
public class ArticleServiceImpl implements IArticleService {

    @Resource
    private ArticleMapper articleMapper;

    @Resource
    private IUserService userService;

    @Resource
    private IBoradService boardService;

    @Override
    public void create(Article article) {
        //校验参数
        if(article==null||article.getUserId()<=0 || StringUtil.isEmpty(article.getContent())
                ||article.getBoardId()<=0 ||
                StringUtil.isEmpty(article.getTitle())){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常  统一抛出ApplicationException
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //设置默认值
        article.setVisitCount(0);  //访问数量
        article.setReplyCount(0);  //回复数量
        article.setLikeCount(0);    //点赞数量
        article.setDeleteState((byte) 0);
        article.setState((byte) 0);
        Date data=new Date();
        article.setCreateTime(data);
        article.setUpdateTime(data);
        //写入数据库
        int row=articleMapper.insertSelective(article);
        if(row<=0){
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        
        // 确保文章ID已被设置
        if (article.getId() == null) {
            log.warn("插入文章成功但未获取到自增ID");
        }
        
        //更新用发帖数
        User user=userService.selectById(article.getUserId());  //获取用户信息
        //没有查找到指定用户信息
        if (user == null) {
            log.warn(ResultCode.FAILED_CREATE.toString()+"发帖失败 userid= "+article.getUserId());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        //调用接口 更新发帖数
        userService.addOneArticleCountById(user.getId());
        //更新板块文章数量
        Board board=boardService.selectById(article.getBoardId());
        if (board == null) {
            log.warn(ResultCode.FAILED_CREATE.toString()+"发帖失败 BoardId= "+article.getBoardId());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        //更新板块文章数量
        boardService.addOneArticleCountById(board.getId());
        //打印日志
        log.info(ResultCode.SUCCESS.toString()+"userid= "+article.getUserId()+" board id= "+article.getBoardId()
        +" Article id= "+article.getId()+" 发帖成功");
    }

    @Override
    public List<Article> selectAll() {
        //调用dao
        List<Article> articles=articleMapper.selectAll();
        return articles;
    }

    @Override
    public List<Article> selectAllWithUserInfo() {
        //调用带用户信息的查询
        List<Article> articles = articleMapper.selectAllWithUserInfo();
        return articles != null ? articles : new ArrayList<>();
    }

    @Override
    public List<Article> getAllByBoardId(Long boardId) {
        //非空校验
        if(boardId<=0||boardId==null){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //校验板块是否存在
        Board board = boardService.selectById(boardId);
        if(board==null){
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString()+"boardId= "+boardId);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }
        //调用dao
        List<Article> articles=articleMapper.selectAllByBoardId(boardId);
        return articles;
    }
    
    @Override
    public List<Article> getAllByBoardIdWithInfo(Long boardId) {
        //非空校验
        if(boardId<=0||boardId==null){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //校验板块是否存在
        Board board = boardService.selectById(boardId);
        if(board==null){
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString()+"boardId= "+boardId);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }
        //调用带用户信息的dao查询
        List<Article> articles = articleMapper.selectAllByBoardIdWithInfo(boardId);
        return articles != null ? articles : new ArrayList<>();
    }

    @Override
    public Article selectDetailById(Long id){
        //非空校验
        if(id==null||id<=0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article = articleMapper.selectDetailByIdWithInfo(id);
        //如果查询失败
        if(article==null){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        
        // 如果文章已被禁用，仅返回文章信息，不增加访问次数
        if (article.getState() == 1) {
            return article;
        }
        
        //更新帖子的访问次数
        Article updateArticle=new Article();
        updateArticle.setId(article.getId());
        updateArticle.setVisitCount(article.getVisitCount()+1);
        //保存到将更新的数据保存到数据库
        int row=articleMapper.updateByPrimaryKeySelective(updateArticle);
        //更新失败
        if(row!=1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //之前查询的访问数量是之前的 但是我们已经对其进行更新操作 实际数据库里访问量已经+1 我们手动给查询到的结果+1
        //和数据库保持一致
        article.setVisitCount(article.getVisitCount()+1);
        //返回结果
        return article;
    }

    @Override
    public List<Article> selectByUserId(Long userId, Integer page, Integer size) {
        //非空校验
        if(userId==null||userId<=0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //判断用户id 是否存在
        User user=userService.selectById(userId);
        if(user==null){
            //打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        
        // 默认值处理
        if (page == null || page < 1) {
            page = 1;
        }
        if (size == null || size < 1) {
            size = 10;
        }
        
        // 计算分页起始位置
        int offset = (page - 1) * size;
        
        // 尝试使用带详细信息的查询方法
        try {
            List<Article> articles = articleMapper.selectByUserIdWithInfo(userId, offset, size);
            if(articles != null && !articles.isEmpty()) {
                return articles;
            }
        } catch (Exception e) {
            log.warn("获取带详细信息的用户文章失败，fallback到基本查询: " + e.getMessage());
        }
        
        // 如果详细查询失败，使用基本查询方法
        List<Article> articles = articleMapper.selectByUserId(userId, offset, size);
        if(articles == null) {
            articles = new ArrayList<>();
        }
        return articles;
    }
    
    @Override
    public int countUserArticles(Long userId) {
        //非空校验
        if(userId==null||userId<=0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        
        //判断用户id 是否存在
        User user=userService.selectById(userId);
        if(user==null){
            //打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        
        // 获取用户文章总数
        Integer count = articleMapper.countUserArticles(userId);
        return count != null ? count : 0;
    }

    @Override
    public void modify(Long id, String title, String content, String tags, String summary) {
        if(id == null || id < 1){
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE,"文章id不合法"));
        }
        if(StringUtil.isEmpty(title)){
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE,"文章标题不能为空"));
        }
        if(title.length() > 128){
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE,"文章标题不得超过128个字符"));
        }
        if(StringUtil.isEmpty(content)){
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE,"文章内容不能为空"));
        }
        
        Article article = this.articleMapper.selectByPrimaryKey(id);
        if(article == null || article.getDeleteState() == 1){
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        
        article.setTitle(title);
        article.setContent(content);
        article.setTags(tags);
        article.setSummary(summary);
        article.setUpdateTime(new Date());
        
        articleMapper.updateByPrimaryKeyWithBLOBs(article);
    }

    @Override
    public void modifyWithBoard(Long id, String title, String content, Long boardId, String tags, String summary) {
        if(id == null || id < 1){
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE,"文章id不合法"));
        }
        if(StringUtil.isEmpty(title)){
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE,"文章标题不能为空"));
        }
        if(title.length() > 128){
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE,"文章标题不得超过128个字符"));
        }
        if(StringUtil.isEmpty(content)){
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE,"文章内容不能为空"));
        }
        if(boardId == null || boardId < 1){
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE,"板块id不合法"));
        }
        
        Article article = this.articleMapper.selectByPrimaryKey(id);
        if(article == null || article.getDeleteState() == 1){
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        
        // 获取原始板块ID
        Long oldBoardId = article.getBoardId();
        
        // 更新文章信息
        article.setTitle(title);
        article.setContent(content);
        article.setBoardId(boardId);
        article.setTags(tags);
        article.setSummary(summary);
        article.setUpdateTime(new Date());
        
        // 更新文章
        articleMapper.updateByPrimaryKeyWithBLOBs(article);
        
        // 只有当板块改变时才更新板块文章计数
        if (!oldBoardId.equals(boardId)) {
            // 原板块文章数-1
            boardService.subOneArticleCountById(oldBoardId);
            // 新板块文章数+1
            boardService.addOneArticleCountById(boardId);
        }
    }

    @Override
    public Article selectById(Long id) {
       if(id==null||id<=0){
           //打印日志
           log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
           //抛出异常
           throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
       }
       log.debug("查询文章，ID: {}", id);
       Article article = articleMapper.selectByPrimaryKey(id);
       // 检查文章是否存在或已删除
       if (article == null) {
           log.debug("文章不存在，ID: {}", id);
           return null;
       }
       
       // 如果文章已被删除，记录日志并返回null
       if (article.getDeleteState() == 1) {
           log.debug("文章已被删除，ID: {}，删除状态: {}", id, article.getDeleteState());
           return null;
       }
       
       log.debug("成功查询到文章，ID: {}，删除状态: {}", id, article.getDeleteState());
       return article;
    }

    @Override
    public void thumbsUpById(Long id) {
        //非空校验
        if(id==null||id<=0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //获取帖子详情
        Article article = articleMapper.selectByPrimaryKey(id);
        //校验帖子
        if(article==null||article.getDeleteState()==1){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        if(article.getState()==1){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }
        //构造数据对象
        Article updateArticle =new Article();
        //修改点赞字段
        updateArticle.setId(article.getId());
        updateArticle.setLikeCount(article.getLikeCount()+1);
        updateArticle.setUpdateTime(new Date());
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row!=1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        
        // 更新文章作者的获赞数
        userService.addOneLikeCountById(article.getUserId());
    }

    @Override
    public void cancelThumbsUpById(Long id) {
        //非空校验
        if(id==null||id<=0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //获取帖子详情
        Article article = articleMapper.selectByPrimaryKey(id);
        //校验帖子
        if(article==null||article.getDeleteState()==1){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        if(article.getState()==1){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }
        // 确保点赞数不会小于0
        int newLikeCount = Math.max(0, article.getLikeCount() - 1);
        //构造数据对象
        Article updateArticle = new Article();
        //修改点赞字段，减少点赞数
        updateArticle.setId(article.getId());
        updateArticle.setLikeCount(newLikeCount);
        updateArticle.setUpdateTime(new Date());
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row!=1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        
        // 更新文章作者的获赞数
        userService.subOneLikeCountById(article.getUserId());
    }

    @Override
    public void deleteById(Long id) {
        //校验参数
        if(id==null||id<=0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article=articleMapper.selectByPrimaryKey(id);
        if(article.getDeleteState()==1||article==null){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString()+"article id= "+id);
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        if(article.getState()==1){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }
        //校验通过  删除操作其实是个更新操作 将文章的删除字段设置为1
        //板块文章数量-1 用户文章数量-1
        Article updateArticle=new Article();
        updateArticle.setId(article.getId());
        updateArticle.setDeleteState((byte) 1);
        updateArticle.setUpdateTime(new Date());
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row!=1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        userService.subOneArticleCountById(article.getUserId());
        boardService.subOneArticleCountById(article.getBoardId());
        log.info("删除帖子成功 article id=  "+article.getId()+"user id= "+article.getUserId()+"board id= "+article.getBoardId());
    }

    @Override
    public void addOneReplyCountById(Long id) {
        //校验参数
        if(id==null||id<=0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article = articleMapper.selectByPrimaryKey(id);
        //校验帖子
        if(article==null||article.getDeleteState()==1){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        if(article.getState()==1){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }
        //校验全部通过 执行回复 +1操作
        //构造更新数据
        Article updateArticle=new Article();
        updateArticle.setId(article.getId());
        updateArticle.setUpdateTime(new Date());
        updateArticle.setReplyCount(article.getReplyCount()+1);
        int row=articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row!=1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //更新成功
    }

    @Override
    public List<Article> getAllArticles() {
        List<Article> articles = articleMapper.getAllArticles();
        return articles != null ? articles : new ArrayList<>();
    }
    
    @Override
    public void updateArticleState(Long articleId, Byte state) {
        // 参数校验
        if (articleId == null || articleId <= 0 || (state != 0 && state != 1)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        
        // 检查文章是否存在
        Article article = articleMapper.selectByPrimaryKey(articleId);
        if (article == null || article.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString() + " articleId=" + articleId);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        
        // 更新文章状态
        int result = articleMapper.updateArticleState(articleId, state);
        if (result != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString() + " 更新文章状态失败 articleId=" + articleId);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        
        log.info("文章状态更新成功: articleId=" + articleId + ", state=" + state);
    }
    
    @Override
    public void adminDeleteArticle(Long articleId) {
        // 参数校验
        if (articleId == null || articleId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        
        // 检查文章是否存在
        Article article = articleMapper.selectByPrimaryKey(articleId);
        if (article == null || article.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString() + " articleId=" + articleId);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        
        // 执行删除操作（逻辑删除）
        Article updateArticle = new Article();
        updateArticle.setId(articleId);
        updateArticle.setDeleteState((byte) 1);
        updateArticle.setUpdateTime(new Date());
        
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString() + " 管理员删除文章失败 articleId=" + articleId);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        
        // 更新板块文章数和用户文章数
        userService.subOneArticleCountById(article.getUserId());
        boardService.subOneArticleCountById(article.getBoardId());
        
        log.info("管理员删除文章成功: articleId=" + articleId + ", userId=" + article.getUserId() + ", boardId=" + article.getBoardId());
    }

    @Override
    public int countTotalArticles() {
        return articleMapper.countTotalArticles();
    }
    
    @Override
    public int countTodayNewArticles() {
        return articleMapper.countTodayNewArticles();
    }

    @Override
    public void incrementVisitCount(Long id) {
        // 参数校验
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        
        // 先查询文章，确保存在
        Article article = articleMapper.selectByPrimaryKey(id);
        if (article == null || article.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        
        // 如果文章已被禁用，不增加访问次数
        if (article.getState() == 1) {
            return;
        }
        
        // 更新访问次数
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setVisitCount(article.getVisitCount() + 1);
        
        // 保存到数据库
        int rows = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (rows != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        
        log.info("文章访问量增加成功: id={}, 当前访问量={}", id, article.getVisitCount() + 1);
    }

    @Override
    public Map<String, Object> getArticlesByPage(int page, int size, String keyword, String status, String sort, String order) {
        // 参数校验
        if (page <= 0) {
            page = 1;
        }
        if (size <= 0) {
            size = 10;
        }
        
        // 计算偏移量
        int offset = (page - 1) * size;
        
        // 处理排序字段，默认按创建时间降序
        if (sort == null || sort.trim().isEmpty()) {
            sort = "createTime";
        }
        
        // 处理排序方向，默认降序
        if (order == null || order.trim().isEmpty() || 
            (!order.equalsIgnoreCase("asc") && !order.equalsIgnoreCase("desc"))) {
            order = "desc";
        }
        
        try {
            // 查询文章列表
            List<Article> articles = articleMapper.getArticlesByPage(offset, size, keyword, status, sort, order);
            
            // 查询符合条件的总数
            int total = articleMapper.countArticlesByCondition(keyword, status);
            
            // 获取所有用户和板块，用于映射ID到名称
            List<User> allUsers = userService.getAllUsers();
            Map<Long, String> userMap = new HashMap<>();
            for (User user : allUsers) {
                userMap.put(user.getId(), user.getUsername());
            }
            
            List<Board> allBoards = boardService.getAllBoards();
            Map<Long, String> boardMap = new HashMap<>();
            for (Board board : allBoards) {
                boardMap.put(board.getId(), board.getName());
            }
            
            // 为每篇文章添加用户名和板块名
            List<Map<String, Object>> enrichedArticles = articles.stream().map(article -> {
                Map<String, Object> enrichedArticle = new HashMap<>();
                // 复制文章所有属性
                enrichedArticle.put("id", article.getId());
                enrichedArticle.put("boardId", article.getBoardId());
                enrichedArticle.put("userId", article.getUserId());
                enrichedArticle.put("title", article.getTitle());
                enrichedArticle.put("content", article.getContent());
                enrichedArticle.put("visitCount", article.getVisitCount());
                enrichedArticle.put("replyCount", article.getReplyCount());
                enrichedArticle.put("likeCount", article.getLikeCount());
                enrichedArticle.put("state", article.getState());
                enrichedArticle.put("deleteState", article.getDeleteState());
                enrichedArticle.put("createTime", article.getCreateTime());
                enrichedArticle.put("updateTime", article.getUpdateTime());
                
                // 添加用户名和板块名
                enrichedArticle.put("author", userMap.getOrDefault(article.getUserId(), "未知用户"));
                enrichedArticle.put("category", boardMap.getOrDefault(article.getBoardId(), "未知板块"));
                
                // 添加前端需要的状态字段
                if (article.getState() == 1) {
                    enrichedArticle.put("status", "DISABLED");
                } else if (article.getIsPinned() != null && article.getIsPinned() == 1) {
                    enrichedArticle.put("status", "PINNED");
                } else {
                    enrichedArticle.put("status", "PUBLISHED");
                }
                
                return enrichedArticle;
            }).collect(Collectors.toList());
            
            // 将结果封装到Map中返回
            Map<String, Object> result = new HashMap<>();
            result.put("list", enrichedArticles);
            result.put("total", total);
            
            return result;
        } catch (Exception e) {
            log.error("分页获取文章列表失败", e);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }
    
    @Override
    public void updateArticlePinState(Long articleId, Byte isPinned) {
        // 参数校验
        if (articleId == null || articleId <= 0 || (isPinned != 0 && isPinned != 1)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        
        // 检查文章是否存在
        Article article = articleMapper.selectByPrimaryKey(articleId);
        if (article == null || article.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString() + " articleId=" + articleId);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        
        // 更新文章置顶状态
        Article updateArticle = new Article();
        updateArticle.setId(articleId);
        updateArticle.setIsPinned(isPinned);
        updateArticle.setUpdateTime(new Date());
        
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString() + " 更新文章置顶状态失败 articleId=" + articleId);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        
        log.info("文章置顶状态更新成功: articleId=" + articleId + ", isPinned=" + isPinned);
    }
}
